package com.ibeeking.found.upms.s.rest.controller.v1;

import com.ibeeking.found.common.annotation.LoginUser;
import com.ibeeking.found.common.constants.GlobalConstant;
import com.ibeeking.found.common.constants.HeaderNounConstant;
import com.ibeeking.found.common.db.annotation.IgnoreDS;
import com.ibeeking.found.common.entity.CurrentUser;
import com.ibeeking.found.common.entity.LoginUserDTO;
import com.ibeeking.found.common.enums.LoginRoleEnum;
import com.ibeeking.found.upms.api.common.query.AccountLoginQuery;
import com.ibeeking.found.upms.s.rest.service.IShopPermissionService;
import com.ibeeking.found.upms.s.rest.service.IShopUserRoleService;
import com.ibeeking.found.upms.s.rest.service.IShopUserService;
import com.ibeeking.found.upms.service.common.bo.ShopUserRoleBO;
import com.ibeeking.found.upms.service.common.param.ModifyMobileParam;
import com.ibeeking.found.upms.service.common.param.ShopUserParam;
import com.ibeeking.found.upms.service.common.param.UserFindPwdParam;
import com.ibeeking.found.upms.service.common.param.UserModifyPwdParam;
import com.ibeeking.found.upms.service.common.query.ShopUserPageQuery;
import com.ibeeking.found.upms.service.common.vo.*;
import com.ibeeking.nematos.constants.enums.OperateLogTypeEnum;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.log.annotation.Log;
import com.ibeeking.nematos.utils.base.BaseValidationGroup;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.data.TreeFastUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName UserController控制器
 * @Description 商户员工管理
 * @Author ibeeking
 * @Date 2020-12-02 15:29
 **/
@RestController
@RequestMapping("/b/user/v1")
public class ShopUserController {

    @Resource
    private IShopUserService shopUserService;
    @Resource
    private IShopUserRoleService shopUserRoleService;
    @Resource
    private IShopPermissionService shopPermissionService;

    @Log(logType = OperateLogTypeEnum.QUERY, describe = "获取当前登录用户权限菜单")
    @GetMapping(value = "/currentPermission")
    public List<CurrentPermissionVO> currentPermission(@LoginUser(isFull = true) CurrentUser currentUser, HttpServletRequest request) {
        List<CurrentPermissionVO> result = shopPermissionService.queryEffectiveList(currentUser, request.getHeader(HeaderNounConstant.JWT_JTI));
        return TreeFastUtils.listToTree(result, GlobalConstant.PARENT_ID);
    }

    @Log(logType = OperateLogTypeEnum.QUERY, describe = "分页查询商户用户列表")
    @PostMapping(value = "/pageList")
    public Page<ShopUserPageVO> pageList(@LoginUser CurrentUser currentUser, @RequestBody ShopUserPageQuery query) {
        return shopUserService.pageList(currentUser.getCurrentShop().getShopId(), query);
    }

    @Log(logType = OperateLogTypeEnum.QUERY, describe = "获取当前登录用户信息")
    @IgnoreDS
    @GetMapping(value = "/currentInfo")
    public CurrentUserVO currentInfo(@LoginUser CurrentUser currentUser) {
        return shopUserService.currentInfo(currentUser.getId());
    }

    @Log(logType = OperateLogTypeEnum.SAVE, describe = "新增商户员工信息")
    @PostMapping(value = "/add")
    public Boolean add(@LoginUser CurrentUser currentUser, @RequestBody @Validated(BaseValidationGroup.Insert.class) ShopUserParam param) {
        return shopUserService.add(currentUser.getCurrentShop().getShopId(), param);
    }

    @Log(logType = OperateLogTypeEnum.SAVE, describe = "修改商户员工信息")
    @PostMapping(value = "/modify")
    public Boolean modify(@RequestBody @Validated(BaseValidationGroup.Update.class) ShopUserParam param) {
        return shopUserService.modify(param);
    }

    @Log(logType = OperateLogTypeEnum.QUERY, describe = "查询商户员工信息")
    @GetMapping(value = "/view/{id}")
    public ShopUserVO view(@PathVariable("id") Long id) {
        return shopUserService.view(id);
    }

    @Log(logType = OperateLogTypeEnum.MODIFY, describe = "解锁/锁定商户用户")
    @GetMapping(value = "/changeStatus/{id}/{status}")
    public Boolean changeStatus(@LoginUser CurrentUser currentUser, @PathVariable("id") Long id, @PathVariable("status") Integer status) {
        return shopUserService.changeStatus(currentUser.getCurrentShop().getShopId(), id, status);
    }

    @Log(logType = OperateLogTypeEnum.DEL, describe = "删除商户员工")
    @GetMapping(value = "/del/{id}")
    public Boolean del(@LoginUser CurrentUser currentUser, @PathVariable("id") Long id) {
        return shopUserService.del(currentUser.getCurrentShop().getShopId(), id);
    }

    @Log(logType = OperateLogTypeEnum.DEL, describe = "离职商户员工")
    @GetMapping(value = "/quit/{id}")
    public Boolean quit(@LoginUser CurrentUser currentUser, @PathVariable("id") Long id) {
        if (currentUser.getId().equals(id)) {
            throw new BusinessException("不能离职自己");
        }
        return shopUserService.quit(currentUser.getCurrentShop().getShopId(), id);
    }

    @Log(logType = OperateLogTypeEnum.MODIFY, describe = "修改商户用户密码")
    @PostMapping(value = "/modifyPwd")
    public Boolean modifyPwd(@LoginUser CurrentUser currentUser, @RequestBody @Validated UserModifyPwdParam userModifyPwdParam) {
        if (LoginRoleEnum.TENANT.name().equals(currentUser.getLoginRole())) {
            throw new BusinessException("请登录租户端进行密码修改");
        }
        return shopUserService.modifyPwd(currentUser.getId(), userModifyPwdParam);
    }

    /**
     * 重置密码
     *
     * @param id
     * @return
     */
    @Log(logType = OperateLogTypeEnum.MODIFY, describe = "重置商户用户密码")
    @GetMapping(value = "/resetPwd/{id}")
    public Boolean resetPwd(@PathVariable("id") Long id) {
        return shopUserService.resetPwd(id);
    }

    /**
     * 找回密码
     *
     * @param userFindPwdParam
     * @return
     */
    @Log(logType = OperateLogTypeEnum.MODIFY, describe = "找回商户用户密码")
    @IgnoreDS
    @PostMapping(value = "/findPwd")
    public Boolean findPwd(@RequestBody @Validated UserFindPwdParam userFindPwdParam) {
        return shopUserService.findPwd(userFindPwdParam);
    }

    @Log(logType = OperateLogTypeEnum.MODIFY, describe = "查询商铺用户角色id列表")
    @GetMapping(value = "/queryRoleIdsByUserId/{userId}")
    public List<String> queryRoleIdsByUserId(@LoginUser CurrentUser currentUser, @PathVariable("userId") @NotNull(message = "userId不能为空") Long userId) {
        List<ShopUserRoleBO> userRoleBOS = shopUserRoleService.queryRoleIdsByUserId(currentUser.getCurrentShop().getShopId(), userId);
        if (Collections3.isEmpty(userRoleBOS)) {
            return Collections3.emptyList();
        }
        return userRoleBOS.parallelStream().map(userRoleBO -> String.valueOf(userRoleBO.getRoleId())).distinct().collect(Collectors.toList());
    }

    @Log(logType = OperateLogTypeEnum.QUERY, describe = "查询用户管辖店铺列表")
    @IgnoreDS
    @GetMapping(value = "/shops")
    public List<ChoiceShopVO> shops(@LoginUser CurrentUser currentUser) {
        return shopUserService.shops(currentUser);
    }

    @Log(logType = OperateLogTypeEnum.DEL, describe = "注销商户账号")
    @IgnoreDS(value = "#tenantId")
    @GetMapping(value = "/logOff/{tenantId}/{shopId}")
    public Boolean logOff(@LoginUser CurrentUser currentUser, @PathVariable("tenantId") @NotNull(message = "租户id必填") Integer tenantId, @PathVariable("shopId") @NotNull(message = "商户id必填") Long shopId) {
        return shopUserService.logOff(shopId, currentUser.getId());
    }

    @Log(logType = OperateLogTypeEnum.QUERY, describe = "查询是否存在账号")
    @IgnoreDS
    @GetMapping(value = "/queryAccount/{mobile}")
    public Boolean del(@PathVariable("mobile") @NotBlank(message = "手机号必填") String mobile) {
        AccountLoginQuery query = new AccountLoginQuery();
        query.setMobile(mobile);
        LoginUserDTO loginUserDTO = shopUserService.queryAccountLogin(query);
        return null != loginUserDTO.getId();
    }

    @Log(logType = OperateLogTypeEnum.MODIFY, describe = "修改手机号")
    @PostMapping(value = "/modifyMobile")
    public Boolean modifyMobile(@LoginUser CurrentUser currentUser, @RequestBody @Validated ModifyMobileParam param) {
        if (LoginRoleEnum.TENANT.name().equals(currentUser.getLoginRole())) {
            throw new BusinessException("请登录租户端进行手机号码修改");
        }
        return shopUserService.modifyMobile(currentUser, param);
    }
}
